package com.mamingchao.basics.designpattern.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * 树形结构
 *
 * Created by mamingchao on 2020/10/15.
 */
public class CompositeTester {
    public static void main(String[] args) {
        BranchNode root = new BranchNode("java 设计模式");
        BranchNode chapter1 = new BranchNode("组合模式");
        BranchNode chapter2 = new BranchNode("享元模式");
        BranchNode section11 = new BranchNode("section11");
        chapter1.addNode(section11);

        LeafNode node111 = new LeafNode("node111");
        chapter2.addNode(node111);
        root.addNode(chapter1);
        root.addNode(chapter2);


        tree(root,0);
    }

    static void tree(Node node,int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print("  ");
        }
        node.print();
        if (node instanceof BranchNode) {
            for(Node n : ((BranchNode) node).childrenNodes){
                tree(n,depth+1);
            }
        }
    }
}

abstract class Node{
    String name;
    abstract void print();
}

/**
 * 最基础的、最底层的元数据
 */
class LeafNode extends Node {

    LeafNode(String name){
        this.name = name;
    }

    @Override
    void print() {
        System.out.println(this.name);
    }
}

class BranchNode extends Node {

    BranchNode(String name){
       this.name = name;
    }

    List<Node> childrenNodes = new ArrayList<>();

    public void addNode(Node node){
        this.childrenNodes.add(node);
    }

    @Override
    void print() {
        System.out.println(this.name);
    }
}

